﻿//Renders tiles

var tileRenderer = function () {

    var render = function (tileDiv, sceneId) {
        if (sceneId == null) {
            sceneId = 0;
        }
        var size = tileDiv.data().scenes[sceneId].size,
            template = tileDiv.data().templates[size],
            formatterFunc = tileDiv.data().formatter;

        tileDiv.html(template);
        if (formatterFunc != null) {
            formatterFunc(tileDiv);
        }

        setPlayersDroppable();
                
        $('.PlayerOnField').droppable({
            accept: '.Player',
            hoverClass: 'dragover',
            tolerance: 'pointer',
            drop: function (event, ui) { dropPlayer(ui.draggable, this); }
        });

        function dropPlayer(src, target)
        {
            if(target.innerHTML != null & target.innerHTML.trim() != "")
            {
                var newPlayer = $("<div class='Player' >" + target.innerHTML + "</div>");
                $(".Players").append(newPlayer);
                setPlayersDroppable();
            }
            
            target.innerHTML = src[0].innerHTML;
            src.detach();
            setNewGameDroppable();
        }

        function setPlayersDroppable()
        {
            $('.Player').draggable({
                opacity: 0.9, zIndex: 5000, revert: 'invalid', revertDuration: 500,
                start: function (event, ui) {
                    $(this).addClass('PlayerActive');
                    $('#NewGame').droppable("destroy");
                },
                stop: function (event, ui) {
                    $(this).removeClass('PlayerActive');
                    setNewGameDroppable();
                }
            });

        }

        function setNewGameDroppable()
        {  
            sceneStateManager.setDroppable($('#NewGame'));                  
        }
    };

    return {
        render: render
    };

} ();




